import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class AveragePrice {
    public static void main(String[] args) {
        File file = new File("C:/Users/20833/Desktop/11.txt");
        int count = 0;
        double sum = 0.0;

        // 检查文件是否存在和可读
        if (file.exists()) {
            System.out.println("文件存在");
        }

        if (file.canRead()) {
            System.out.println("文件可读");
        }

        // 读取文件并计算价格
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
            String str;
            while ((str = br.readLine()) != null) {
                System.out.println("读取行: " + str);
                // 使用 Scanner 处理每一行，提取价格
                try (Scanner sc = new Scanner(str)) {
                    sc.useDelimiter("[^0-9.]+");
                    while (sc.hasNextDouble()) {
                        double price = sc.nextDouble();
                        count++;
                        sum += price;
                        System.out.println("价格: " + price);
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("读取文件时出错: " + e.getMessage());
            return;
        }

        // 计算平均价格
        if (count > 0) {
            double average = sum / count;
            String averageStr = String.format("%.3f", average);
            System.out.println("平均价格: " + averageStr);

            // 将平均价格写入文件，使用 UTF-8 编码
            try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")) {
                writer.write("\n平均价格: " + averageStr + "元/台\n");
            } catch (IOException e) {
                System.out.println("写入文件时出错: " + e.getMessage());
            }
        } else {
            System.out.println("没有找到价格数据。");
        }
    }
}
